<template>
  <div class="attraction-management">
    <el-card>
      <div slot="header" class="clearfix" style="display: flex; align-items: center; justify-content: center;">

        <el-input v-model="searchKeyword" placeholder="请输入景点名称/详情/地址" style="width: 200px;"
          @keyup.enter="search"></el-input>
        <el-button style="margin-left: 5px;" type="primary" icon="el-icon-search" @click="search"></el-button>
        <span style="position: absolute;">景点管理</span>
        <el-button style="margin-left: auto; padding: 3px 0" type="text" @click="showAddDialog">添加景点</el-button>
      </div>
      <el-table :data="attractions" style="width: 100%">
        <el-table-column label="景点封面" width="150">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="baseUrl + scope.row.coverImage"
              :preview-src-list="[baseUrl + scope.row.coverImage]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="景点名称" width="200"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column prop="description" label="景点描述"></el-table-column>
        <el-table-column prop="ticketPrice" label="门票价格" width="100">
          <template slot-scope="scope">
            {{ scope.row.ticketPrice === 0 ? '免费' : scope.row.ticketPrice }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="primary" @click="handleReview(scope.row)" :disabled="scope.row.reviewCount === 0">查看评论</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.current"
        :page-sizes="[5, 10, 20, 50]" :page-size.sync="page.size" layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </el-card>

    <!-- //修改表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="currentAttraction" label-width="100px">
        <el-form-item label="景点名称">
          <el-input v-model="currentAttraction.name" :disabled="isViewMode"></el-input>
        </el-form-item>
        <el-form-item label="景点描述">
          <el-input type="textarea" v-model="currentAttraction.description" :disabled="isViewMode"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="currentAttraction.address" :disabled="isViewMode"></el-input>
        </el-form-item>
        <el-form-item label="开放时间">
          <el-time-picker v-model="currentAttraction.openTime.start" format="HH:mm" value-format="HH:mm"
            :disabled="isViewMode" placeholder="开始时间">
          </el-time-picker>
          <span style="margin: 0 10px;">至</span>
          <el-time-picker v-model="currentAttraction.openTime.end" format="HH:mm" value-format="HH:mm"
            :disabled="isViewMode" placeholder="结束时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="门票价格">
          <el-input-number v-model="currentAttraction.ticketPrice" :precision="2" :step="0.1"
            :disabled="isViewMode"></el-input-number>
        </el-form-item>
        <el-form-item label="景点封面" v-if="!isViewMode">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <div style="position: relative;" v-if="currentAttraction.coverImage">
              <el-image style="width: 150px; height: 150px" :src="baseUrl + currentAttraction.coverImage"
                :preview-src-list="[baseUrl + currentAttraction.coverImage]">
              </el-image>
              <el-button @click="removeCoverImage()" circle size="mini" type="danger" icon="el-icon-delete"
                style="position: absolute; top: 5px; right: 5px;">
              </el-button>
            </div>
            <el-upload v-if="!currentAttraction.coverImage" action="" :auto-upload="false"
              :on-change="handleCoverImageChange" :show-file-list="false" style="align-self: flex-end;">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>

          </div>

        </el-form-item>
        <el-form-item label="景点详情图" v-if="!isViewMode">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <div v-for="(image, index) in currentAttraction.detailImages" :key="index" style="position: relative;">
              <el-image v-if="currentAttraction.detailImages && currentAttraction.detailImages.length > 0"
                style="width: 150px; height: 150px" :src="baseUrl + image"
                :preview-src-list="currentAttraction.detailImages.map(img => baseUrl + img)">
              </el-image>
              <el-button @click="removeDetailImage(index)" circle size="mini" type="danger" icon="el-icon-delete"
                style="position: absolute; top: 5px; right: 5px;">
              </el-button>
            </div>
            <el-upload action="" :auto-upload="false" :on-change="handleDetailImagesChange" multiple :limit="5"
              :file-list="detailImagesList" style="align-self: flex-end;" :show-file-list="true">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="浏览量" v-if="isViewMode">
          <el-input v-model="currentAttraction.viewCount" disabled></el-input>
        </el-form-item>
        <el-form-item label="评论量" v-if="isViewMode">
          <el-input v-model="currentAttraction.reviewCount" disabled></el-input>
        </el-form-item>
        <el-form-item label="收藏量" v-if="isViewMode">
          <el-input v-model="currentAttraction.collectionCount" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="景点详情">
          <el-input type="textarea" v-model="currentAttraction.description" :disabled="isViewMode"></el-input>
        </el-form-item> -->
        <el-form-item label="景点封面" v-if="isViewMode">
          <el-image style="width: 200px; height: 200px" :src="baseUrl + currentAttraction.coverImage"
            :preview-src-list="[baseUrl + currentAttraction.coverImage]">
          </el-image>
        </el-form-item>
        <el-form-item label="景点详情图"
          v-if="isViewMode && currentAttraction.detailImages && currentAttraction.detailImages.length > 0">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <el-image v-for="(image, index) in currentAttraction.detailImages" :key="index"
              style="width: 150px; height: 150px" :src="baseUrl + image"
              :preview-src-list="currentAttraction.detailImages.map(img => baseUrl + img)">
            </el-image>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
    
    <!-- 评论弹窗 -->
    <el-dialog title="景点评论" :visible.sync="reviewDialogVisible" width="70%">
      <el-table :data="reviews" style="width: 100%">
        <el-table-column label="用户头像" width="100">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px" :src="baseUrl + scope.row.avatarUrl"
              :preview-src-list="[baseUrl + scope.row.avatarUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="content" label="评论内容"></el-table-column>
        <el-table-column prop="rating" label="评分" width="80"></el-table-column>
        <el-table-column prop="reviewCreatedAt" label="评论时间" width="180"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDeleteReview(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import base from '@/utils/base.js';

export default {
  data() {
    return {
      attractions: [],
      dialogVisible: false,
      dialogTitle: '',
      searchKeyword: '',
      currentAttraction: {
        name: '',
        description: '',
        address: '',
        openTime: {
          start: '',
          end: ''
        },
        ticketPrice: 0,
        coverImage: '',
        detailImages: [],
        viewCount: 0,
        reviewCount: 0,
        collectionCount: 0
      },
      isAdd: false,
      isEdit: false,
      isViewMode: false,
      detailImagesList: [],
      page: {
        current: 1,
        size: 5,
        total: 0
      },
      attractionList: [],
      baseUrl: base.url,
      reviewDialogVisible: false,
      reviews: []
    }
  },
  methods: {
    //查看评论
    handleReview(row) {
      this.$http.get(`/reviews/${row.attractionId}`)
        .then(response => {
          if (response && response.code === 200) {
            this.reviews = response.reviews;
            // console.log('获取评论成功:', this.reviews);
            this.reviewDialogVisible = true;
          } else {
            this.$message.error(response.message || '获取评论失败');
          }
        })
        .catch(error => {
          console.error('获取评论失败:', error);
          this.$message.error('获取评论失败: ' + (error.message || '未知错误'));
        });
    },
    //删除评论
    handleDeleteReview(row) {
      this.$confirm('确认删除该评论吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/review?reviewId=${row.reviewId}&attractionId=${row.attractionId}`)
          .then(response => {
            if (response && response.code === 200) {
              this.$message.success('删除成功');
              this.reviews = this.reviews.filter(review => review.reviewId !== row.reviewId);
            } else {
              this.$message.error(response.message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除评论失败:', error);
            this.$message.error('删除评论失败: ' + (error.message || '未知错误'));
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //封面图片删除
    removeCoverImage() {
      this.currentAttraction.coverImage = '';
    },
    //详情图片删除
    removeDetailImage(index) {
      this.currentAttraction.detailImages.splice(index, 1);
      this.detailImagesList.splice(index, 1);
    },
    //获取景点总数
    loadTotal(isSearch) {
      const apiUrl = isSearch ? '/admin/searchAttractionCount' : '/admin/attractionCount';
      this.$http.get(apiUrl, {
        params: {
          keyword: this.searchKeyword
        }
      }).then(response => {
        if (response && response.code === 200) {
          this.page.total = response.count;
        }
      }).catch(error => {
        console.error('获取景点总数失败:', error);
        this.$message.error('获取景点总数失败: ' + (error.message || '未知错误'));
      });
    },

    //加载景点数据
    fetchAttractions() {
      console.log('当前页码:', this.page.current);
      const lastId = this.page.current > 1 ? (this.page.current - 1) * this.page.size + 1 : 1;
      //获取景点总数
      const apiUrl = this.searchKeyword ? '/search' : '/attractions';
      // console.log("发送请求数据", data)
      this.$http.get(apiUrl, {
        params: {
          lastId: this.searchKeyword ? 1 : lastId,
          limit: this.page.size,
          keyword: this.searchKeyword
        }
      }).then(response => {

        console.log('获取景点数据:', response);
        if (response && response.count && response.attractions) {
          this.attractions = response.attractions;
        } else if (response.count == 0) {
          this.$message('暂无结果');
        } else {
          throw new Error('Invalid API response format');
        }
      }).catch(error => {
        console.error('获取景点数据失败:', error);
        this.$message.error('获取景点数据失败: ' + (error.message || '未知错误'));
        this.attractions = [];
        this.page.total = 0;
      });
    },

    //添加景点的弹出层
    showAddDialog() {
      this.dialogTitle = '添加景点';
      this.currentAttraction = {
        name: '',
        description: '',
        address: '',
        openTime: {
          start: '',
          end: ''
        },
        ticketPrice: 0,
        coverImage: '',
        detailImages: [],
        viewCount: 0,
        reviewCount: 0,
        collectionCount: 0
      };
      this.detailImagesList = [],
      this.isEdit = false;
      this.isViewMode = false;
      this.isAdd = true;
      this.dialogVisible = true;
    },
    //修改按钮
    handleEdit(row) {
      this.dialogTitle = '编辑景点';
      this.currentAttraction = { ...row };
      if (typeof row.detailImages === 'string') {
        try {
          this.currentAttraction.detailImages = JSON.parse(row.detailImages);
        } catch (e) {
          console.error('解析detailImages失败:', e);
          this.currentAttraction.detailImages = [];
        }
      }
      //格式化开放时间
      if (typeof row.openTime === 'string') {
        const [start, end] = row.openTime.split('-');
        this.currentAttraction.openTime = { start, end };
      }
      this.isEdit = true;
      this.isAdd = false;
      this.isViewMode = false;
      this.dialogVisible = true;
    },
    //查看按钮
    handleView(row) {
      this.dialogTitle = '查看景点';
      this.currentAttraction = { ...row };
      if (typeof row.detailImages === 'string') {
        try {
          this.currentAttraction.detailImages = JSON.parse(row.detailImages);
        } catch (e) {
          console.error('解析detailImages失败:', e);
          this.currentAttraction.detailImages = [];
        }
      }
      if (typeof row.openTime === 'string') {
        const [start, end] = row.openTime.split('-');
        this.currentAttraction.openTime = { start, end };
      }
      this.isEdit = false;
      this.isAdd = false;
      this.isViewMode = true;
      this.dialogVisible = true;
    },
    handleDelete(row) {
      console.log('删除景点:', row);
      this.$confirm('确认删除该景点吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/admin/deleteAttraction/${row.attractionId}`)
          .then(response => {
            if (response && response.code === 200) {
              this.$message.success('删除成功');
              this.fetchAttractions();
              this.loadTotal();
            } else {
              this.$message.error(response.message || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除景点失败:', error);
            this.$message.error('删除景点失败: ' + (error.message || '未知错误'));
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submitForm() {


      if (this.isViewMode) {
        console.log("当前状态查看");
      }
      if (this.isAdd) {
        console.log("当前状态添加");
      }
      if (this.isEdit) {
        console.log("当前状态修改");
      }
      // TODO: 根据isEdit调用添加或更新API
      if (this.isViewMode) {
        this.dialogVisible = false;
        return;
      }
      if (this.isEdit || this.isAdd) {
        //更新景点数据
        let Attraction = { ...this.currentAttraction };
        //确保detailImages是数组
        if (!Array.isArray(Attraction.detailImages)) {
          Attraction.detailImages = [];
        }
        //将当前登录的景点详情图片数组转换为字符串
        Attraction.detailImages = JSON.stringify(this.currentAttraction.detailImages);
        //将openTime对象合并为字符串
        if (this.currentAttraction.openTime && this.currentAttraction.openTime.start && this.currentAttraction.openTime.end) {
          Attraction.openTime = `${this.currentAttraction.openTime.start}-${this.currentAttraction.openTime.end}`;
        }
        if (this.isAdd) {
          console.log("添加景点数据", Attraction);
        } else {
          console.log("修改景点数据", Attraction);
        }


        const apiUrl = this.isEdit ? '/admin/updateAttraction' : '/admin/addAttraction';
        let isAdd = this.isAdd;
        this.$http.post(apiUrl, Attraction)
          .then(response => {
            if (response && response.code === 200) {
              this.$message.success('景点更新成功');
              this.dialogVisible = false;
              if (isAdd) {
                this.page.current = Math.ceil((this.page.total + 1) / this.page.size);
                this.page.total += 1;
                // this.fetchAttractions();
              }
              this.fetchAttractions();
            } else {
              this.$message.error(response.message || '景点更新失败');
            }
          })
          .catch(error => {
            console.error('景点更新失败:', error);
            this.$message.error('景点更新失败: ' + (error.message || '未知错误'));
          });
      }
    },
    handleSizeChange(val) {
      console.log('每页显示数量:', val);
      this.page.size = val;
      this.fetchAttractions();
    },
    handleCurrentChange(val) {
      console.log('当前页码:', val);
      this.page.current = val;
      this.fetchAttractions();
    },
    search() {
      console.log("点击search", this.searchKeyword);
      this.loadTotal(true);
      this.fetchAttractions();

    },
    //修改封面图片
    handleCoverImageChange(file) {
      const formData = new FormData();
      formData.append('file', file.raw);
      console.log('当前封面图:', this.currentAttraction.coverImage);

      this.$http.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response && response.code === 200) {
          this.currentAttraction.coverImage = response.url;
          console.log('上传封面图片成功:', response.url);
          this.$message.success('封面图片上传成功');
        } else {
          this.$message.error(response.message || '封面图片上传失败');
        }
      }).catch(error => {
        console.error('上传封面图片失败:', error);
        this.$message.error('上传封面图片失败: ' + (error.message || '未知错误'));
      });
    },
    handleDetailImagesChange(file, fileList) {
      console.log('当前详情图:', this.currentAttraction.detailImages);
      const formData = new FormData();
      formData.append('file', file.raw);

      this.$http.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        if (response && response.code === 200) {
          console.log('上传详情图片成功:', response.url);
          this.$message.success('详情图片上传成功');
          // 将新上传的图片URL添加到详情图片数组中
          this.currentAttraction.detailImages = [
            ...(this.currentAttraction.detailImages || []),
            response.url
          ];
          this.detailImagesList = fileList;
        } else {
          this.$message.error(response.message || '详情图片上传失败');
          this.detailImagesList = this.detailImagesList.filter(item => item.uid !== file.uid);
        }
      }).catch(error => {
        console.error('上传详情图片失败:', error);
        this.$message.error('上传详情图片失败: ' + (error.message || '未知错误'));
        this.detailImagesList = this.detailImagesList.filter(item => item.uid !== file.uid);
      });
    },
  },

  created() {
    // console.log('AttractionManagement组件创建base',base.url);
    this.loadTotal();
    this.fetchAttractions();
  },
  watch: {
    searchKeyword(oldeval, newVal) {
      //监听searchKeyword变化
      console.log('searchKeyword变化旧:', oldeval);
      console.log('searchKeyword变化新:', newVal);
      if (!newVal) {
        this.page.current = 1;
      }
    }
  }
}
</script>

<style scoped>
.attraction-management {
  padding: 20px;
}
</style>